import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:industry_net/base/common/util.dart';
import 'package:industry_net/base/component/marquee/controller.dart';

class MarqueePage extends StatelessWidget {
  MarqueePage({Key? key, required this.text, this.style}) : super(key: key) {
    state.text = text;
    state.width = paintWidthWithTextStyle(style ?? _defaultStyle());
  }
  final controller = Get.put(MarqueeController());
  final state = Get.find<MarqueeController>().state;
  final String text;
  final TextStyle? style;

  TextStyle _defaultStyle() {
    return TextStyle(
      color: ColorsUtil.title,
      fontSize: 13.sp,
      overflow: TextOverflow.clip,
    );
  }

  double paintWidthWithTextStyle(TextStyle style) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(text: state.text, style: style),
        maxLines: 1,
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.size.width;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MarqueeController>(builder: (_) {
      return Flexible(
        key: state.key,
        fit: FlexFit.tight,
        child: Container(
          alignment: Alignment.center,
          child: ListView(
            physics: const NeverScrollableScrollPhysics(),
            controller: state.scrollCtrl,
            scrollDirection: Axis.horizontal,
            padding: EdgeInsets.zero,
            children: [
              _getItem(),
              Container(
                width: state.fixWidth,
              ),
              _getItem(),
              Container(
                width: state.fixWidth,
              ),
            ],
          ),
        ),
      );
    });
  }

  Widget _getItem() {
    return Container(
      width: state.width,
      alignment: Alignment.centerLeft,
      child: Text(
        text,
        maxLines: 1,
        style: style ?? _defaultStyle(),
      ),
    );
  }
}
